import React, { useMemo, useRef, useState } from 'react';
import { Select, Spin, Empty } from 'antd';

import debounce from 'lodash/debounce';


function DebounceSelect({ fetchOptions, debounceTimeout = 800, ...props }) {
  const [fetching, setFetching] = useState(false);
  const [options, setOptions] = useState([]);
  const fetchRef = useRef(0);

  const debounceFetcher = useMemo(() => {
    const loadOptions = (value) => {
      fetchRef.current += 1;
      const fetchId = fetchRef.current;
      setOptions([]);
      setFetching(true);

      fetchOptions(value).then((newOptions) => {
        if (fetchId !== fetchRef.current) {
          // for fetch callback order
          return;
        }

        setOptions(newOptions);
        setFetching(false);
      });
    };

    return debounce(loadOptions, debounceTimeout);
  }, [fetchOptions, debounceTimeout]);

  return (
    <Select
      filterOption={false}
      showSearch
      onSearch={debounceFetcher}
      loading={fetching}
      onFocus={() => {
        if (fetchRef.current === 0) {
          setFetching(true)
          debounceFetcher()
        }
      }}
      notFoundContent={fetching ? <Spin size="small" /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无数据" />}
      {...props}
      options={options}
    />
  );
}

export default DebounceSelect;